import { computed, ref } from "vue";
import type { FormItemContext } from "../../libs/tokens";
import { castArray } from "../../libs/utils";
import type { FormItemProp } from "../e-form-item/props";
import type { Arrayable } from "../../libs/utils/types";
export function useFormLabelWidth() {
  const potentialLabelWidthArr = ref<number[]>([]);

  const autoLabelWidth = computed(() => {
    if (!potentialLabelWidthArr.value.length) return "0";
    // 取potentialLabelWidthArr中的最大值
    const max = Math.max(...potentialLabelWidthArr.value);
    return max ? `${max}px` : "";
  });
  // 获取potentialLabelWidthArr中某个值的坐标
  function getLabelWidthIndex(width: number) {
    const index = potentialLabelWidthArr.value.indexOf(width);
    if (index === -1) {
      // debugWarn(SCOPE, `unexpected width ${width}`)
    }
    return index;
  }
  // 替换labelWidth
  function registerLabelWidth(val: number, oldVal: number) {
    if (val && oldVal) {
      const index = getLabelWidthIndex(oldVal);
      potentialLabelWidthArr.value.splice(index, 1, val);
    } else if (val) {
      potentialLabelWidthArr.value.push(val);
    }
  }
  // 删除LabelWidth
  function deregisterLabelWidth(val: number) {
    const index = getLabelWidthIndex(val);
    if (index > -1) {
      potentialLabelWidthArr.value.splice(index, 1);
    }
  }

  return {
    autoLabelWidth,
    registerLabelWidth,
    deregisterLabelWidth,
  };
}
export const filterFields = (
  fields: FormItemContext[],
  props: Arrayable<FormItemProp>
) => {
  // props转为数组
  const normalized = castArray(props);
  // normalized长度大于0，则返回过滤后的fields
  return normalized.length > 0
    ? fields.filter((field) => field.prop && normalized.includes(field.prop))
    : fields;
};
